package com.lingjtx.common.redis.topic;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisSubscriberMessage {

    // 在此类中处理各种订阅消息，业务处理
    private final Map<String, RedisSubscriberListener> subscriberListenerMap;

    public RedisSubscriberMessage(Map<String, RedisSubscriberListener> subscriberListenerMap) {
        this.subscriberListenerMap = subscriberListenerMap;
    }

    public RedisSubscriberListener getHandler(String beanName) {
        return subscriberListenerMap.get(beanName); // 可按 beanName 获取
    }

    public void handle(String topic, JSONObject data) {
        // 在发布消息的时候严格按照规范书写，必须以 channel:开头，channel:用户ID:业务:业务ID:意图。比如 channel:user_id:order:order_id:create（新增一条订单消息）
        if (topic.startsWith("channel:")) {
            // 要处理的业务过程
            String msgId = data.getString("messageId");
            for (RedisSubscriberListener redisSubscriberListener : subscriberListenerMap.values()) {
                redisSubscriberListener.onMessage(msgId, topic, data.get("data"));
            }
        }
    }
}
